﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using XrmLibrary.Enums.Attributes;

namespace XrmLibrary.Extensions
{
    internal static class EnumExtensions
    {
        /// <summary>
        /// Will get the string value for a given enums value, this will
        /// only work if you assign the StringValue attribute to
        /// the items in your enum.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        internal static String GetDescription(this Enum value)
        {
            EnumDescriptionAttribute attribute = value.GetDescriptionAttribute();
            return attribute != null ? attribute.StringValue : null;
        }

        internal static EnumDescriptionAttribute GetDescriptionAttribute(this Enum value)
        {
            // Get the type
            Type type = value.GetType();

            // Get fieldinfo for this type
            FieldInfo fieldInfo = type.GetField(value.ToString(CultureInfo.InvariantCulture));

            // Get the stringvalue attributes
            EnumDescriptionAttribute[] attributes = fieldInfo.GetCustomAttributes(typeof(EnumDescriptionAttribute), false) as EnumDescriptionAttribute[];

            if (attributes == null)
            {
                return null;
            }

            // Return the first if there was a match.
            return attributes.Length > 0 ? attributes[0] : null;
        }
    }
}
